<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
  public $layout = '//layouts/column2';
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xCCCCCC,
		    'minLength'=>7
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
  
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('deny', 
				'actions'=>array('login','forgotPassword','resetPassword'),
				'users'=>array('@'),
			),
			array('deny', 
				'actions'=>array('logout'),
				'users'=>array('?'),
			),
		);
	}
	
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
	  $this->layout = '//layouts/column1';
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}
	
	
	// User guide page.
	public function actionUserGuide()
	{
	  $this->layout = '//layouts/column1';
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('userguide');
	}
	
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Cám ơn bạn đã liên hệ với chúng tôi. Chúng tôi sẽ trả lời cho bạn sớm nhất có thể.');
				$this->refresh();
			}
			else {
			  $output = getErrors($model);
			  print json_encode(array('result'=>array('error'=>$output)));
			}
			die;
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];			
			// validate user input and redirect to the previous page if valid
			if($model->validate()) {
				$user = User::model()->findByAttributes(array('username'=>strtolower($model->username),'active'=>1));
				if(!empty($user)) {
					if($user->deleted==1) {
						Yii::app()->user->setFlash('notice','Tài khoản của bạn đã bị xóa khỏi hệ thống.');
					}
					if($user->deleted==0 && $model->login()){
						
						$statusID = Status::model()->findByAttributes(array('status'=>'ONLINE'))->statusID;
						$user_status = UserStatus::model()->findByAttributes(array('userID'=>$user->ID));
						$user_status->statusID = $statusID;
						$user_status->update();
						
						$this->redirect(Yii::app()->user->returnUrl);
					}
				}
				else {
					Yii::app()->user->setFlash('notice','Tài khoản của bạn chưa được kích hoạt.');
				}
			}
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		$statusID = Status::model()->findByAttributes(array('status'=>'OFFLINE'))->statusID;
		$user_status = UserStatus::model()->findByAttributes(array('userID'=>Yii::app()->user->id));
		$user_status->statusID = $statusID;
		$user_status->update();
		
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	/**
	 * Display forgotPassword page
	 */
	public function actionForgotPassword()
	{
	  $this->layout = '//layouts/column1';
	  $model = new UserProfile('forgot');
	  
	  if(isset($_POST['UserProfile']))
	  {
	    $model->attributes = $_POST['UserProfile'];
	    if($model->validate()) {
	      $user_profile = UserProfile::model()->findByAttributes(array('email'=>$model->email));
	      $user = User::model()->findByPk($user_profile->userID);
	      if(!empty($user)){
  	      $user->reset = 1;
  	      $user->update();
	      }
	      /**
	       * if send mail, attach link below to go Reset page
	       */
	      $this->redirect(Yii::app()->baseUrl.'/site/resetPassword/id/'.md5($user_profile->userID.$user_profile->email));
	    } 
	  }
	  $this->render('forgotPassword', array('model'=>$model));
	}
	
	public function actionResetPassword()
	{
	  $this->layout = '//layouts/column1';
	  $id = isset($_GET['id'])?$_GET['id']:0;
    $user_profile = Yii::app()->db->createCommand()
          ->select('u.ID,u.reset,u.deleted')
          ->from("tbl_user_profile as t")
          ->join("tbl_user as u","u.ID=t.userID")
          ->where("md5(CONCAT(t.userID,t.email))='$id'")
          ->queryRow();
	  if($id!='' && !empty($user_profile)) {
      $model = array();
      if($user_profile['deleted']==1) {
        Yii::app()->user->setFlash('notice', 'Tài khoản của bạn đã bị xóa khỏi hệ thống.');
        $this->redirect(Yii::app()->baseUrl);
      }
      else {
        if($user_profile['reset']==0) {
          Yii::app()->user->setFlash('notice', 'Mật khẩu của bạn đã được khôi phục.');
          $this->redirect(Yii::app()->baseUrl);
        }
        else {
          $id = $user_profile['ID'];
          $model = new User('reset');
          if(isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if($model->validate()) {
	            $user = User::model()->findByPk($id);
  						$user->password = md5($model->password);
  						$user->reset = 0;
  						$user->update();
  						Yii::app()->user->setFlash('success', 'Khôi phục mật khẩu thành công');
  						$this->redirect(Yii::app()->homeUrl);
            }
          }
	        $this->render('resetPassword',array('model'=>$model));
        }
      }
	  } 
	  else {
	    $this->redirect(Yii::app()->baseUrl);
	  }
	}
}